﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Video;


public class VideoBG : MonoBehaviour {

    VideoPlayer vp = null;
    AudioSource aus = null;

    private static VideoBG instance = null;
    public static VideoBG GetInstance ()
    {
        return instance;
    }

    private void Awake()
    {
        instance = this;
        vp = gameObject.GetComponent<VideoPlayer>();
        aus = gameObject.GetComponentInChildren<AudioSource>();
        vp.prepareCompleted += OnPrepareCompleted;
    }

    void OnPrepareCompleted(VideoPlayer v)
    {

        v.Play();
        aus.Play();
    }

    public void _PlayLocal(string urlVideo, string urlAudio)
    {
        if (string.IsNullOrEmpty(urlVideo) || string.IsNullOrEmpty(urlAudio) )
            return;



        string urlLocal = ResLoader.Url2LocalPath(urlVideo);

        vp.url = urlLocal;


        Loading.GetInstance().StartLoading();
            ResLoader.Load(urlAudio, null, (www) =>
            {

                AudioClip ac = WWWAudioExtensions.GetAudioClip(www);
                aus.clip = ac;
                vp.Prepare();

                Resources.UnloadUnusedAssets();
                System.GC.Collect();

                Loading.GetInstance().EndLoading();
            }, true, true);
        
    }

    public static void PlayLocal(string urlVideo, string urlAudio)
    {
        instance._PlayLocal(urlVideo, urlAudio);
    }

    public void _Close()
    {
        vp.Stop();
        aus.Stop();
    }

    public static void Close()
    {
        instance._Close();
    }

    public void _Replay()
    {
        vp.Stop();
        aus.Stop();

        vp.Play();
        aus.Play();
    }

    public static void Replay()
    {
        instance._Replay();
    }

    public void _Pause()
    {
        vp.Pause();
        aus.Pause();
    }

    public static void Pause()
    {
        instance._Pause();
    }

    public void _Play()
    {
        vp.Play();
        aus.Play();
    }

    public static void Play()
    {
        instance._Play();
    }
}
